import RootSiblingsManager from 'react-native-root-siblings';
import type { MessageOptions } from './types';
import MessageBox from './box';

const createMessage = (opts: MessageOptions) => {
  return new Promise(resolve => {
    let rootNode: RootSiblingsManager | null = null;
    const destroy = () => {
      rootNode?.destroy();
      rootNode = null;
      resolve(undefined);
    }
    rootNode = new RootSiblingsManager(
      <MessageBox
        {...opts}
        afterClose={destroy}
      />
    );
  });
}

export const message = {
  success: (text: string) => {
    return createMessage({
      type: 'success',
      text,
    });
  },
  error: (text: string) => {
    return createMessage({
      type: 'error',
      text,
    });
  },
  info: (text: string) => {
    return createMessage({
      type: 'info',
      text,
    });
  }
}

export default message;